import React from 'react'
import {
  Pagination,
  Table,
  Switch,
  Row,
  Col,
  Card,
  message,
  Modal,
  Button
} from 'antd'
import _ from 'lodash'
import { connect } from 'react-redux'
import {
  maintaskFindRealHiTaskApi,
  stopTaskJobApi,
  resetTaskJobApi,
  projectFindBypageApi,
  maintaskFindBypageApi,
  productFindApi
} from '../api/ajax'

const columns = (props, loadData, pageNum, showModal) => [
  {
    title: '任务编号',
    dataIndex: 'taskCode',
    key: '2',
    width: 150
  },
  {
    title: '项目名称',
    dataIndex: 'projectName',
    key: '3',
    width: 100
  },
  {
    title: '项目单位',
    dataIndex: 'branch',
    key: '16',
    width: 100
  },
  {
    title: '实时状态',
    dataIndex: 'problemType',
    key: '15',
    width: 130,
    render: (text, record, index) => {
      let obj = {
        0: '正常',
        1: '源端错误',
        2: '目的端错误'
      }
      if (_.isNil(text)) return '未执行 '
      return obj[text]
    }
  },
  {
    title: '任务状态',
    dataIndex: 'status',
    key: '4',
    width: 100,
    render: (text, record, index) => {
      let obj = {
        1: '正常',
        2: '暂停',
        3: '异常',
        4: '过期',
        5: '正在执行'
      }
      return obj[text]
    }
  },
  {
    title: '上次运行时间',
    dataIndex: 'newDate',
    key: '5',
    width: 150
  },
  {
    title: '最近传输文件数',
    dataIndex: 'fileNum',
    key: '6',
    width: 150
  },
  {
    title: '源产品名称',
    dataIndex: 'productName',
    key: '7',
    width: 120,
    render: (text, record) => (
      <span>
        <span>{text}</span>
        <button className="button-a" onClick={() => showModal(record.sourceId)}>
          查看
        </button>
      </span>
    )
  },
  {
    title: '目标地址',
    dataIndex: 'address',
    key: '12'
  },
  {
    title: '切换',
    fixed: 'right',
    key: '14',
    width: 100,
    render: (text, record) => {
      if (record.status === 1) {
        return (
          <span>
            <Switch
              checkedChildren="开"
              unCheckedChildren="关"
              defaultChecked={true}
              onChange={async c => {
                stopTaskJobApi({
                  id: record.id,
                  projectId: record.projectId,
                  taskCode: record.taskCode
                }).then(v => {
                  loadData(pageNum)
                })
              }}
            />
          </span>
        )
      } else if (record.status === 2) {
        return (
          <span>
            <Switch
              checkedChildren="开"
              unCheckedChildren="关"
              defaultChecked={false}
              onChange={async c => {
                resetTaskJobApi({
                  id: record.id,
                  projectId: record.projectId,
                  taskCode: record.taskCode
                }).then(() => loadData(pageNum))
              }}
            />
          </span>
        )
      } else {
        return null
      }
    }
  }
]

class Home extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      currentPage: 1,
      pageNum: 1,
      pageSize: 5,
      sourceId: '',
      tableSource: [],
      aimsIds: '',
      branch: '',
      projectId: '',
      status: '',
      projectSource: [],
      visible: false,
      productForm: {},
      taskInfo: []
    }
  }
  componentWillMount() {
    this.loadBoard()
    this.loadData(1)
    this.reflashTimer = setInterval(() => {
      this.loadBoard()
      this.loadData(this.state.pageNum)
    }, 5000)
  }
  componentWillUnmount() {
    clearInterval(this.reflashTimer)
  }
  loadBoard = () => {
    maintaskFindRealHiTaskApi().then(v => {
      this.setState({ taskInfo: _.isNull(v) ? {} : v })
    })
  }
  loadData = pageNum => {
    const {
      pageSize,
      sourceId,
      aimsIds,
      projectId,
      status,
      branch
    } = this.state
    this.setState({ currentPage: pageNum, pageNum })
    projectFindBypageApi().then(v => {
      let {
        list: { results }
      } = v
      if (_.isNil(results)) results = []
      this.setState({
        projectSource: results
      })
    })
    maintaskFindBypageApi({
      pageNum,
      pageSize,
      sourceId,
      aimsIds,
      projectId,
      status,
      branch
    })
      .then(v => {
        let {
          list: { totalRecord, results }
        } = v
        if (_.isNil(results)) results = []
        this.setState({
          totalRecord,
          tableSource: results
        })
      })
      .catch(e => console.error(e))
  }

  showModal = async sourceId => {
    productFindApi({ id: sourceId })
      .then(v => {
        this.setState({
          productForm: v,
          visible: true
        })
      })
      .catch(error => {
        message.error('请求超时')
      })
  }

  render() {
    const { taskInfo } = this.state
    return (
      <div className="home" style={{ padding: '10px', background: '#fff' }}>
        <div className="home-head" style={{ paddingTop: 0 }}>
          <div>
            <h3>任务概况(当日统计)</h3>
            <Row gutter={16}>
              <Col span={8}>
                <Card title="任务统计">
                  <div>
                    总任务数：
                    <span
                      className="font-blod-large"
                      style={{ color: '#FFD86E' }}
                    >
                      {taskInfo.allSUm}
                    </span>
                  </div>
                </Card>
              </Col>
              <Col span={8}>
                <Card title="文件传输统计">
                  <div>
                    传输文件总数：
                    <span
                      className="font-blod-large"
                      style={{ color: '#49A9EE' }}
                    >
                      {taskInfo.fileSum}
                    </span>
                  </div>
                </Card>
              </Col>
              <Col span={8}>
                <Card title="故障统计">
                  <div>
                    总共发生故障（次）：
                    <span
                      className="font-blod-large"
                      style={{ color: '#F3857C' }}
                    >
                      {taskInfo.errorSum}
                    </span>
                  </div>
                </Card>
              </Col>
            </Row>
          </div>
          <h3 style={{ marginTop: '10px' }}>任务报表</h3>
        </div>
        <div>
          <Table
            dataSource={this.state.tableSource}
            scroll={{ x: 1500 }}
            columns={columns(
              this.props,
              this.loadData,
              this.state.pageNum,
              this.showModal
            )}
            pagination={false}
            rowKey={record => record.id}
          />
          <div className="home-body-page">
            <Pagination
              total={this.state.totalRecord}
              pageSize={this.state.pageSize}
              current={this.state.currentPage}
              onChange={pageNum => {
                this.setState({ pageNum, currentPage: pageNum })
                this.loadData(pageNum)
              }}
              showTotal={total => `共${total}条数据`}
            />
          </div>
        </div>
        {this.state.visible && (
          <Modal
            visible={this.state.visible}
            title="源产品信息"
            onCancel={() => this.setState({ visible: false })}
            footer={
              <Button
                type="primary"
                onClick={() => this.setState({ visible: false })}
              >
                确定
              </Button>
            }
          >
            源产品编号:
            {this.state.productForm && this.state.productForm.productCode}
            <br />
            源产品名称:
            {this.state.productForm && this.state.productForm.productName}
            <br />
            文件名称:{this.state.productForm && this.state.productForm.fileName}
            <br />
            扩展名:{this.state.productForm && this.state.productForm.extenName}
            <br />
            源地址:
            {this.state.productForm && this.state.productForm.sourceAddress}
            <br />
            可访问目标名称:
            {this.state.productForm && this.state.productForm.userName}
          </Modal>
        )}
      </div>
    )
  }
}

export default connect(state => ({
  state
}))(Home)
